package cn.changeforyou.utils;

import java.io.File;

public class FileDirectoryUtils {
	
	/**
	 * 在文件上层搜索指定文件
	 *
	 * @param targetName
	 * @param file
	 * @return
	 */
	public static File searchFileUponFile(String targetName, File file) {
		File parentFile = file.getParentFile();
		File[] children = parentFile.listFiles();
		for (File child : children) {
			if (child.getName().equals(targetName)) {
				return child;
			}
		}
		return searchFileUponFile(targetName, parentFile);
	}
	
	/**
	 * 根据文件中搜索子文件
	 *
	 * @param targetName
	 * @param file
	 * @return
	 */
	public static File searchFileInFile(String targetName, File file) {
		if (!file.isDirectory()) {
			if (file.getName().equals(targetName)) {
				return file;
			}
			return null;
		} else {
			File[] children = file.listFiles();
			for (File child : children) {
				File resultFile = searchFileInFile(targetName, child);
				if (null != resultFile) {
					return resultFile;
				}
			}
			return null;
		}
	}
	
	/**
	 * 搜索文件前缀
	 *
	 * @param targetName
	 * @param file
	 * @return
	 */
	public static File searchFileInFileByPrefix(String targetName, File file) {
		if (!file.isDirectory()) {
			if (file.getName().startsWith(targetName)) {
				return file;
			}
			return null;
		} else {
			File[] children = file.listFiles();
			for (File child : children) {
				File resultFile = searchFileInFile(targetName, child);
				if (null != resultFile) {
					return resultFile;
				}
			}
			return null;
		}
	}
}
